package dao

import (
	"booksPro/model"
	"booksPro/utils"
)

// 向购物车表中 插入购物一条购物车数据
func AddCart(cart *model.Cart) error {
	sqlStr := "insert into carts(id,total_count,total_amount,user_id) values(?,?,?,?)"
	_, err := utils.Db.Exec(sqlStr, cart.CartID, cart.GetTotalCount(), cart.GetTotalAmount(), cart.UserID)
	if err != nil {
		return err
	}
	//获取购物车中所有购物项
	cartItems := cart.CartItems
	for _, cartItem := range cartItems {
		//将每一个购物项 都插入到 购物项表中
		AddCartItem(cartItem)
	}
	return nil
}

func GetCartByUserID(userID int) (*model.Cart, error) {
	sqlStr := "select id,total_count,total_amount,user_id from carts where user_id = ?"
	row := utils.Db.QueryRow(sqlStr, userID)
	cart := &model.Cart{}
	err := row.Scan(&cart.CartID, &cart.TotalCount, &cart.TotalAmount, &cart.UserID)
	if err != nil {
		return nil, err
	}
	cartItems, _ := GetCartItemsByCartID(cart.CartID)
	cart.CartItems = cartItems
	return cart, nil
}

// 更新购物车中图书的总数量和金额
func UpateCart(cart *model.Cart) error {
	sqlStr := "update carts set total_count =? , total_amount = ?  where id = ? "
	_, err := utils.Db.Exec(sqlStr, cart.GetTotalCount(), cart.GetTotalAmount(), cart.CartID)
	if err != nil {
		return err
	}
	return nil
}

func DeleteCartByCartID(cartID string) error {
	sqlStr := "delete from carts where id =?"
	_, err := utils.Db.Exec(sqlStr, cartID)
	if err != nil {
		return err
	}
	return nil
}
